package com.hcbd.tdwt.ui.fuda.common.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.GpsStatus;
import android.location.LocationManager;
import android.location.OnNmeaMessageListener;
import android.os.Build;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.hcbd.tdwt.R;
import com.hcbd.tdwt.base.BaseActivity;
import com.hcbd.tdwt.base.Listener.InfoInterface;
import com.hcbd.tdwt.util.StringUtil;
import com.pangu.bdsdk2021.entity.terminaltwo.BDGGAInfo;
import com.pangu.bdsdk2021.entity.terminaltwo.BDGSVInfo;
import com.pangu.bdsdk2021.entity.terminaltwo.BDRMCInfo;
import com.hcbd.tdwt.ui.xingyu.fragment.PositionInfoFragment_;
import com.hcbd.tdwt.ui.xingyu.fragment.SatelliteListFragment_;
import com.hcbd.tdwt.ui.xingyu.fragment.SkyMapFragment_;
import com.hcbd.tdwt.ui.xingyu.vo.SatelliteVO;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.CheckedChange;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

@SuppressLint("NonConstantResourceId")
@EActivity(R.layout.activity_position_info_fuda)
public class PositionInfoActivity extends BaseActivity {

    @ViewById(R.id.position_info)
    RadioButton positionInfoRB;
    @ViewById(R.id.sky_map)
    RadioButton skyMapRB;
    @ViewById(R.id.satellite_list)
    RadioButton satelliteRB;
    @ViewById
    TextView title;
    PositionInfoFragment_ positionInfoFragment;
    SatelliteListFragment_ satelliteListFragment;
    SkyMapFragment_ skyMapFragment;
    private List<SatelliteVO> satelliteVOList;
    private TreeMap<String, SatelliteVO> hashMap = new TreeMap<>();
    private LocationManager mLocationManager;
    private final int LOCATION_CODE=15;
    private BDRMCInfo bdrmcInfo;
    private BDGSVInfo bdgsvInfo;
    private BDGGAInfo bdggaInfo;
    @AfterViews
    protected void init() {
        title.setText("卫星");
        bdrmcInfo=new BDRMCInfo();
        bdgsvInfo= new BDGSVInfo();
        bdggaInfo=new BDGGAInfo();
        positionInfoFragment = new PositionInfoFragment_();
        satelliteListFragment = new SatelliteListFragment_();
        skyMapFragment = new SkyMapFragment_();
        positionInfoRB.setChecked(true);
        satelliteVOList = new ArrayList<>();
        setSkyInfoInterface(skyMapFragment);
        setSatelliteInfoInterface(satelliteListFragment);
        setPositionInterface(positionInfoFragment);
        getLocation();
    }

    public void getLocation() {
        //获取权限（如果没有开启权限，会弹出对话框，询问是否开启权限）
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //请求权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_CODE);
        } else {
            locationInfo();
        }
    }
    @Click
    void headLeft(){
        finish();
    }

    @CheckedChange(R.id.position_info)
    void positionInfoRB(boolean isChecked){
        if(isChecked) {
            switchFragment(positionInfoFragment, R.id.resultLL);
        }
    }
    @CheckedChange(R.id.sky_map)
    void skyMapRB(boolean isChecked){
        if(isChecked) {
            switchFragment(skyMapFragment, R.id.resultLL);
        }
    }
    @CheckedChange(R.id.satellite_list)
    void satelliteRB(boolean isChecked){
        if(isChecked) {
            switchFragment(satelliteListFragment, R.id.resultLL);
        }
    }

    private InfoInterface skyInfoInterface;
    private InfoInterface satelliteInfoInterface;
    private InfoInterface positionInterface;

    public void setSkyInfoInterface(InfoInterface infoInterface){
        this.skyInfoInterface=infoInterface;
    }
    public void setSatelliteInfoInterface(InfoInterface infoInterface){
        this.satelliteInfoInterface=infoInterface;
    }
    public void setPositionInterface(InfoInterface infoInterface){
        this.positionInterface=infoInterface;
    }
    public void initData(BDGSVInfo info){
        SatelliteVO satelliteVO=new SatelliteVO();
        if(StringUtil.isNumeric(info.sv1,info.azl1,info.elv1,info.cno1)){
            satelliteVO.setSv(info.sv1);
            satelliteVO.setCno(info.cno1);
            satelliteVO.setAz(info.azl1);
            satelliteVO.setElv(info.elv1);
            satelliteVO.setSatelliteType(info.satellitesType);
            hashMap.put(info.satellitesType+info.sv1,satelliteVO);
        }
        if(StringUtil.isNumeric(info.sv2,info.azl2,info.elv2,info.cno2)) {
            SatelliteVO satelliteVO2 = new SatelliteVO();
            satelliteVO2.setSv(info.sv2);
            satelliteVO2.setCno(info.cno2);
            satelliteVO2.setAz(info.azl2);
            satelliteVO2.setElv(info.elv2);
            satelliteVO2.setSatelliteType(info.satellitesType);
            hashMap.put(info.satellitesType+info.sv2, satelliteVO2);
        }
        if(StringUtil.isNumeric(info.sv3,info.azl3,info.elv3,info.cno3)) {
            SatelliteVO satelliteVO3 = new SatelliteVO();
            satelliteVO3.setSv(info.sv3);
            satelliteVO3.setCno(info.cno3);
            satelliteVO3.setAz(info.azl3);
            satelliteVO3.setElv(info.elv3);
            satelliteVO3.setSatelliteType(info.satellitesType);
            hashMap.put(info.satellitesType+info.sv3, satelliteVO3);
        }
        if(StringUtil.isNumeric(info.sv4,info.azl4,info.elv4,info.cno4)) {
            SatelliteVO satelliteVO4 = new SatelliteVO();
            satelliteVO4.setSv(info.sv4);
            satelliteVO4.setCno(info.cno4);
            satelliteVO4.setAz(info.azl4);
            satelliteVO4.setElv(info.elv4);
            satelliteVO4.setSatelliteType(info.satellitesType);
            hashMap.put(info.satellitesType+info.sv4, satelliteVO4);
        }
        satelliteVOList.clear();
        for (String key : hashMap.keySet()) {
            satelliteVOList.add(hashMap.get(key));
        }
        skyInfoInterface.onGSVInfo(satelliteVOList);
        satelliteInfoInterface.onGSVInfo(satelliteVOList);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case LOCATION_CODE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED
                        && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    // 权限被用户同意。
                    // 执形我们想要的操作
                    locationInfo();
                } else {
                    toast("没有获取权限无法使用该功能！");
                }
            }
        }
    }
    @SuppressLint("MissingPermission")
    public void locationInfo(){
        if (mLocationManager == null)
            mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mLocationManager.addNmeaListener(onNmeaMessageListener);
        } else {
            mLocationManager.addNmeaListener(mNmeaListener);
        }

    }
    OnNmeaMessageListener onNmeaMessageListener= (s, l) -> receivedNmea(s);

    //$GPGGA,072024.0,2307.582054,N,11321.928800,E,1,07,0.7,45.2,M,-4.0,M,,*76
    //原始数据监听
    GpsStatus.NmeaListener mNmeaListener = (arg0, instruc) -> receivedNmea(instruc);
    public void receivedNmea(String instruc){
        if(instruc.contains("GGA")){
            convertGGAInfo(instruc);
            if(bdggaInfo!=null) {
                positionInterface.onGGAInfo(bdggaInfo);
            }
        }else if(instruc.contains("RMC")){
            build2_1(instruc);
            if(bdrmcInfo!=null) {
                positionInterface.onRMCInfo(bdrmcInfo);
            }
        }else if(instruc.contains("GSV")){
            convertGSVInfo(instruc);
            if(bdgsvInfo!=null){
                initData(bdgsvInfo);
            }
        }
    }
    //GNGGA,071249.988,3209.5304,N,11841.5127,E,0,0,,72.0,M,4.9,M,,*53
    public  void convertGGAInfo(String instruc){
        int xorIndex = instruc.indexOf("*");
        if (xorIndex != -1) {
            instruc = instruc.substring(0, xorIndex);
        }
        String[] instrucs = instruc.split(",",-1);
        if (instrucs.length < 15) {
            return;//长度不足视为无效数据'
        }
        bdggaInfo.positioningMoment=instrucs[1];
        bdggaInfo.latitude=instrucs[2];
        bdggaInfo.latitudeDirection=instrucs[3];
        bdggaInfo.longitude=instrucs[4];
        bdggaInfo.longitudeDirection=instrucs[5];
        bdggaInfo.statusIndication=instrucs[6];
        bdggaInfo.visibleSatellite=instrucs[7];
        bdggaInfo.hdop=instrucs[8];
        bdggaInfo.antennaHeight=instrucs[9];
        bdggaInfo.antennaHeightUnit=instrucs[10];
        bdggaInfo.abnormalElevation=instrucs[11];
        bdggaInfo.satelliteSigLockStatusUnit=instrucs[12];
        bdggaInfo.differentialDataAge=instrucs[13];
        bdggaInfo.differentialStationID=instrucs[14];
    }

    public  void convertGSVInfo(String instruc){
        int xorIndex = instruc.indexOf("*");
        if (xorIndex != -1) {
            instruc = instruc.substring(0, xorIndex);
        }
        String[] instrucs = instruc.split(",",-1);
        if (instrucs.length < 20) return;//长度不足视为无效数据'
        bdgsvInfo.satellitesType=instrucs[0];
        bdgsvInfo.totalNumber=instrucs[1];
        bdgsvInfo.statementNumber=instrucs[2];
        bdgsvInfo.satellitesNumber=instrucs[3];
        bdgsvInfo.sv1=instrucs[4];
        bdgsvInfo.elv1=instrucs[5];
        bdgsvInfo.azl1=instrucs[6];
        bdgsvInfo.cno1=instrucs[7];
        bdgsvInfo.sv2=instrucs[8];
        bdgsvInfo.elv2=instrucs[9];
        bdgsvInfo.azl2=instrucs[10];
        bdgsvInfo.cno2=instrucs[11];
        bdgsvInfo.sv3=instrucs[12];
        bdgsvInfo.elv3=instrucs[13];
        bdgsvInfo.azl3=instrucs[14];
        bdgsvInfo.cno3=instrucs[15];
        bdgsvInfo.sv4=instrucs[16];
        bdgsvInfo.elv4=instrucs[17];
        bdgsvInfo.azl4=instrucs[18];
        bdgsvInfo.cno4=instrucs[19];
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mLocationManager!=null){
            mLocationManager.removeNmeaListener(mNmeaListener);
            mLocationManager.removeNmeaListener(onNmeaMessageListener);
        }
    }

    public void build2_1(String instruc) {
        String[] instrucs = instruc.split(",", -1);
        if (instrucs.length >= 7) {
            bdrmcInfo.utcTime = instrucs[1];
            bdrmcInfo.positionStatus = instrucs[2];
            bdrmcInfo.latitude = instrucs[3];
            bdrmcInfo.latitudeDirection = instrucs[4];
            bdrmcInfo.longitude = instrucs[5];
            bdrmcInfo.longitudeDirection = instrucs[6];
            bdrmcInfo.groundSpeed = instrucs[7];
            bdrmcInfo.groundHeading = instrucs[8];
            bdrmcInfo.date = instrucs[9];
            bdrmcInfo.magneticDeclination = instrucs[10];
            bdrmcInfo.magneticDeclinationDirection = instrucs[11];
            bdrmcInfo.modeIndication = instrucs[12];
        }
    }

}
